package com.kye.addrpicker;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.kye.addrpicker.adapter.CityListAdapter;
import com.kye.addrpicker.adapter.ResultListAdapter;
import com.kye.addrpicker.db.DBManager;
import com.kye.addrpicker.model.City;
import com.kye.addrpicker.model.LocateState;
import com.kye.addrpicker.utils.StringUtils;
import com.kye.addrpicker.view.SideLetterBar;

import java.util.List;

/**
 * Created by harry on 2017/12/22 下午3:44.
 */

public class AddressPickerFragment extends CheckPermissionsFragment implements View.OnClickListener, CheckPermissionsListener {

    private static final String ARG_PARENT_CITY = "parent_city";
    private static final String ARG_FIRST_LEVEL_TITLE = "first_level_title";
    private static final String ARG_NEED_SHOW_CHILD_TITLE = "need_show_child_title";
    private static final String ARG_IS_NETWORK_POINT_QUERY = "is_network_point_query";
    public static final String PARAM_PY_LOCATION = "0";//定位的全拼
    public static final String PARAM_PY_HOT = "1";//热门的全拼
    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private TextView cancelBtn;
    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private List<City> mResultCities;
    private DBManager dbManager;

    private PickerListener mPickerListener;
    private City mParentCity;
    private String mTitle = "";
    private boolean mNeedShowChildTitle = false;
    private boolean mIsNetWorkPointQuery = false;

    public LocationClient mLocationClient = null;
    private BDAbstractLocationListener mBdAbstractLocationListener;

    /**
     * @param parentCity 当前需要查询的父city
     * @return
     */
    public static AddressPickerFragment newInstances(City parentCity) {
        AddressPickerFragment fragment = new AddressPickerFragment();
        if (parentCity != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(ARG_PARENT_CITY, parentCity);
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    public static AddressPickerFragment newFromNetworkPointQueryInstances(City parentCity) {
        AddressPickerFragment fragment = new AddressPickerFragment();
        if (parentCity != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(ARG_PARENT_CITY, parentCity);
            bundle.putString(ARG_FIRST_LEVEL_TITLE, "网点查询");
            bundle.putBoolean(ARG_NEED_SHOW_CHILD_TITLE, true);
            bundle.putBoolean(ARG_IS_NETWORK_POINT_QUERY, true);
            fragment.setArguments(bundle);
        }
        return fragment;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPickerListener = (context instanceof PickerListener) ? (PickerListener) context : null;
    }

    @Override
    public void onResume() {
        if (mNeedShowChildTitle && mParentCity != null) {
            if (!isFirstlevel()) {
                getActivity().setTitle(mParentCity.getFullName());
            } else {
                getActivity().setTitle(mTitle);
            }
        }
        super.onResume();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.cp_fragment_city_list, null);
        Bundle bundle = getArguments();
        try {
            if (bundle != null) {
                mParentCity = (City) bundle.getSerializable(ARG_PARENT_CITY);
                mTitle = bundle.getString(ARG_FIRST_LEVEL_TITLE);
                mNeedShowChildTitle = bundle.getBoolean(ARG_NEED_SHOW_CHILD_TITLE);
                mIsNetWorkPointQuery = bundle.getBoolean(ARG_IS_NETWORK_POINT_QUERY);
            }
        } catch (Exception e) {

        }
        initData();
        initView(rootView);
        if (isFirstlevel()) {
            initLocation();
            //请求权限
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if (mLocationClient != null) {
                    mLocationClient.start();
                }
            } else {
                requestPermissions(getActivity(), neededPermissions, this);
            }
        }
        return rootView;
    }

    /**
     * 是否是第一层
     *
     * @return
     */
    private boolean isFirstlevel() {
        if (mParentCity != null) {
            if (mParentCity.getParentID().equals(AddressPickerActivity.PARAM_PARENT_FIRST)) {
                return true;
            }
        }
        return false;
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mBdAbstractLocationListener = new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation != null) {
                    String city = bdLocation.getCity();
                    String district = bdLocation.getDistrict();
                    if (!TextUtils.isEmpty(city) && (!TextUtils.isEmpty(district))) {
                        String location = StringUtils.extractLocation(city, district);
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
                    } else {
                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    }
                } else {
                    mCityAdapter.updateLocateState(LocateState.FAILED, null);
                }
            }
        };
        mLocationClient.registerLocationListener(mBdAbstractLocationListener);
    }

    private void initData() {
        dbManager = new DBManager(getActivity());
        dbManager.copyDBFile();
        String parrentId = "0";
        if (mParentCity != null) {
            if (!isFirstlevel()) {
                parrentId = mParentCity.getUniqueID();
            }
        }
        mAllCities = dbManager.getCitiesByParentId(parrentId,mIsNetWorkPointQuery);
        if (isFirstlevel()) {//添加定位和热门
            //TODO 这里先注释掉，后面搞清楚热门的和定位的数据如何补全再说
//            mAllCities.add(0, new City(getString(R.string.location), PARAM_PY_LOCATION));
//            mAllCities.add(1, new City(getString(R.string.hot), PARAM_PY_HOT));
        }
//        mCityAdapter = new CityListAdapter(getActivity(), mAllCities, isFirstlevel());
        mCityAdapter = new CityListAdapter(getActivity(), mAllCities, false);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(City city) {
                if (mPickerListener != null) {
                    mPickerListener.onPicked(city);
                }
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(getActivity(), neededPermissions, AddressPickerFragment.this);
                }
            }
        });

        mResultAdapter = new ResultListAdapter(getActivity(), null);
    }

    private void initView(View rootView) {
        mListView = (ListView) rootView.findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);

        TextView overlay = (TextView) rootView.findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) rootView.findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
//        mLetterBar.isFirstLevel(isFirstlevel());
        mLetterBar.isFirstLevel(false);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });

        searchBox = (EditText) rootView.findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
                    mResultCities = dbManager.searchCity(keyword);
                    if (mResultCities == null || mResultCities.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(mResultCities);
                    }
                }
            }
        });

        emptyView = (ViewGroup) rootView.findViewById(R.id.empty_view);
        mResultListView = (ListView) rootView.findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mPickerListener != null) {
                    mPickerListener.onPicked(mResultAdapter.getItem(position));
                }
            }
        });

        clearBtn = (ImageView) rootView.findViewById(R.id.iv_search_clear);
        cancelBtn = (TextView) rootView.findViewById(R.id.tv_search_cancel);

        clearBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_search_clear) {
            searchBox.setText("");
            clearBtn.setVisibility(View.GONE);
            emptyView.setVisibility(View.GONE);
            mResultListView.setVisibility(View.GONE);
            mResultCities = null;
        } else if (i == R.id.tv_search_cancel) {
            getActivity().finish();
        }
    }

    @Override
    public void onGranted() {
        if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    @Override
    public void onDenied(List<String> permissions) {
        Toast.makeText(getActivity(), "权限被禁用，请到设置里打开", Toast.LENGTH_SHORT).show();
        mCityAdapter.updateLocateState(LocateState.FAILED, null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBdAbstractLocationListener != null) {
            mLocationClient.unRegisterLocationListener(mBdAbstractLocationListener);
        }
    }
}
